<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/15
 * Time: 15:48
 */

namespace Lm\Controllers;
use \Admin\Frontend\Controllers\ControllerBase;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\ims\XHImsBoxIn;
use Admin\Models\ims\XHImsBoxOut;
use Admin\Models\ims\XHImsProdIn;
use Admin\Models\ims\XHImsProdOut;
use Admin\Models\ims\XHImsProdType;
use Admin\Models\ims\XHImsProduct;
use Admin\Models\ims\XHImsReceive;
use Admin\Models\ims\XHImsReceiveProds;
use Admin\Models\ims\XHImsReturn;
use Admin\Models\lm\XHLmGoods;
use Admin\Models\lm\XHLmGoodsIn;
use Admin\Models\lm\XHLmGoodsOut;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Modules\Ims;
use Modules\Lm;

class ReceiveController extends ControllerBase
{

    public static $receiveState = [ 0 => '待确认' , 4 => '已领用'];
    public static $returnState  = [ 0 => '待确认' , 4 => '已归还'];
    public static $goodsEnum = ['type' => ['0' => '否', '1' => '是']];


    /**
     * 获取有额外权限的数组
     *
     * @param $tag
     * @return array|bool
     * @throws \Exception
     * create by xjq 20180530
     */
    public function extraPower($tag)
    {
        if (User::isAdmin()) {
            return true;
        }
        $deps    = User::getExtraPower('dep', $tag);
        $userIds = Hrm::getUserByDepId($deps);
        $newArr  = [];
        foreach ($userIds as $ids) {
            $newArr = array_merge($newArr, $ids);
        }
        $newArr = array_values(array_filter($newArr));

        return $newArr;
    }

//    /**
//     * 拦截器覆盖
//     * @param \Phalcon\Mvc\Dispatcher $dispatcher
//     * @return bool|string|void
//     * create by xjq 20180607
//     */
//    public function beforeExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher)
//    {
//        // 这个方法会在每一个能找到的action前执行
//        $userId=Main::getLoginUserInfo('userId');
//        if(!$userId){
//            Main::goLoginPage();
//        }
//    }


    /**
     * 领用列表
     *
     * create by xjq 20180515
     */
    public function receiveListAction()
    {
        if (!UserPower::checkUserPower('Lm_Goods_Receive')) {
            return $this->sendViewError('没有权限');
        }
        Main::showNavPosition();
        Assets::easyUI();
        Assets::sweetAlert2();
        Assets::importJs('js/receive/receiveList.js');
        Assets::importMainJs('assets/easyui/datagrid-detailview.js');
        $this->view->pick('receive/receiveList');
        Template::exists('receiveList', 'list') or die(Main::showMessageModal('houseList 配置文件不存在，请先创建！', 109106002));
        $listButton = $listSearchArr = [];
        if (UserPower::checkUserPower('Lm_Goods_Receive_Add')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if (UserPower::checkUserPower('Lm_Goods_Receive_Del')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if (UserPower::checkUserPower('Lm_Goods_Receive_Confirm')) {
            $listButton[] = array(
                'plain' => 'true',
                'id'    => 'bt_list_confirm',
                'text'  => '领用确认',
                'icon'  => 'fa-qrcode'
            );
        }
        $receiveState    = ['' => '--领用状态--'] + self::$receiveState;
        $consume         = ['' => '--消耗品--'] + self::$goodsEnum['type'];
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_state', 'data' => $receiveState);
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_consume', 'data' => $consume);
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array(
            'type'  => 'button',
            'id'    => 'bt_list_search',
            'text'  => '查找',
            'icon'  => 'fa-search',
            'style' => 'margin-left:10px'
        );
        $this->view->setVars(array(
            'List' => Template::createList('list', 'receiveList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButton),

            ])

        ));
    }

    /**
     * 获取领用列表
     *
     * create by xjq 20180517
     */
    public function getListAction()
    {
        if (!UserPower::checkUserPower('Lm_Goods_Receive')) {
            return $this->sendErrorResponse(401, '缺少权限');
        }
        $key     = $this->request->getPost('key', 'string');
        $state   = $this->request->getPost('state', 'string');
        $consume = $this->request->getPost('consume');
        try {
            $isConsume = false;
            $condition = " a.bDelete = 0 ";
            if (in_array($consume, ['0', '1'])) {
                $condition .= " AND a.iLRId IN (SELECT b.iKeyId FROM `XHIms_ReceiveProds` b WHERE b.bDelete = 0 AND b.bReceive = 1 AND b.iProdId IN (
		        SELECT c.iId FROM `XHLm_Goods` c WHERE c.bDelete = 0 AND c.iType = {$consume} ))";
                $isConsume = $consume;
            }
            if ($key) {
                $condition .= " AND u.sStaffName LIKE '%" . $key . "%' ";
            }
            if ($state || $state === '0') {
                $condition .= " AND a.iState = " . $state;
            }
            $sql  = [
                'columns' => "a.*, u.sStaffName as sUserName",
                'query'   => "SELECT :columns: FROM `XHIms_Receive` a LEFT JOIN `XHHrm_Staff` u ON u.iUserId = a.iReceiveId WHERE {$condition} ORDER BY a.tCreateDate DESC "
            ];
            $data = Main::runSqlPage($sql, ['iState' => self::$receiveState]);

//            $data = Main::runBuilderPage($builder,['iState' => self::$receiveState]);
            $ids   = array_column($data['rows'], 'iLRId');
            $nodes = $this->getNodeArr($ids, 1, $isConsume);
            foreach ($data['rows'] as $index => &$row) {
                $row['mProdList'] = isset($nodes[$row['iLRId']]) ? $nodes[$row['iLRId']] : [];
                if ($row['mDesc']) {
                    $row['mDesc'] = '<span title="' . $row['mDesc'] . '">' . $row['mDesc'] . '</span>';
                }
                $staffInfo = Hrm::getStaffInfo([$row['iReceiveId']]);
                if (isset($staffInfo[$row['iReceiveId']])) {
                    $staffInfo = $staffInfo[$row['iReceiveId']];
                    $row['sUserName'] .= $staffInfo['depName'] ? '(' . $staffInfo['depName'] . ')' : '';
                    $row['phoneNum'] = $staffInfo['phoneNumber'];
                }
            }
            unset($row);
            Main::runUserNameById($data['rows'], ['iCreateUserId'     => 'iCreateUserId',
                                                  'iLastModifyUserId' => 'iLastModifyUserId'
            ], true);
            //修改人和创建人不用职工的名
//            Hrm::runStaffNameByUserId(
//                $data['rows'],
//                ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'],
//                true
//            );
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 根据keyId获取node字段
     * @param $ids
     * @param $receive
     * @param $isConsume
     * @return array
     * create by xjq 20180530
     * modify by qgz 20180719 使用物品表数据
     */
    public function getNodeArr($ids, $receive = 1, $isConsume = false)
    {
        if (!$ids) {
            return [];
        }
        $prods = XHImsReceiveProds::find([
            'columns'    => 'iProdId,iNum,iKeyId,sPhoneNum',
            'conditions' => 'bDelete = 0 and  iKeyId  in ({ids:array}) and bReceive = :receive: ',
            'bind'       => ['ids' => $ids, 'receive' => $receive],
            'order'      => 'iKeyId'
        ])->toArray();

        $params = ['columns' => 'iId, sGoodsName', 'conditions' => 'bDelete = 0'];
        if ($isConsume !== false) {
            $params['conditions'] .= ' AND iType = ' . $isConsume;
        }
        $prodName = XHLmGoods::find($params)->toArray();
        $prodName = array_column($prodName, 'sGoodsName', 'iId');
        $arr      = [];
        foreach ($prods as $prod) {
            if (isset($prodName[$prod['iProdId']])) {
                $arr[$prod['iKeyId']][] = [
                    'name' => $prodName[$prod['iProdId']],
                    'num' => $prod['iNum'],
                    'other' => $prod['sPhoneNum'] ? '<div style="cursor:pointer" title="点击查看手机号" ' .
                               ' class="showPhone" showPhone="' . $prod['sPhoneNum'] . '" ><a>查看手机号</a></div>' : ''
                ];
            }
//            else {
//                $arr[$prod['iKeyId']][] = ['name' => '无该数据名称(id:' . $prod['iProdId'] . ')', 'num' => $prod['iNum']];
//            }
        }
        return $arr;
    }

    /**
     * 获取领用表单
     *
     * create by xjq 20180515
     * modify by qgz 20180719 使用物品表数据
     */
    public function receiveFormAction()
    {
        $this->view->pick('receive/receiveForm');
        Assets::select2();
        Assets::importJs('js/receive/receiveForm.js');
//        $staff = XhhrmStaff::find([
//            'columns' => 'iUserId,sStaffName',
//            'conditions' => 'bDelete= 0 and iStaffStatus = 1 and iUserId is not null'
//        ])->toArray();
        $goods = XHLmGoods::find(['columns' => 'iId, sGoodsName', 'conditions' => 'bDelete = 0'])->toArray();
        $goods = array_column($goods, 'sGoodsName', 'iId');
//        $staff = array_column($staff, 'sStaffName', 'iUserId');
        $staff = Hrm::getUserWithDepName();
        if ($staff) {
            $staffInfoArr = Hrm::getStaffInfo(array_keys($staff));
            foreach ($staff as $key => &$item) {
                if (isset($staffInfoArr[$key]) && $staffInfoArr[$key]['phoneNumber']) {
                    $item .= '_' . $staffInfoArr[$key]['phoneNumber'];
                }
            }
        }
        $this->view->setVars([
            'staffs' => $staff,
            'prods'  => $goods,
        ]);
    }

//    /**
//     * 领用详情
//     *
//     * @param $number
//     * @return string
//     *
//     * create by xjq 20180530
//     */
//    public function receiveDetailAction($number){
//        $this->view->pick('receive/receiveDetail');
//        $receive = XHImsReceive::findFirst([
//            'conditions' => 'bDelete = 0  and sNumber = :sNumber: ',
//            'bind'       => [ 'sNumber' => $number]
//        ]);
//        if ( !$receive ) {
//            return $this->sendViewError('不存在该清单');
//        }
//        $receive = $receive->toArray();
//        $prods = XHImsReceiveProds::find([
//            'conditions' => 'bDelete = 0  and iPLId = :iPLId: ',
//            'bind'       => ['iPLId' => $receive['iLRId']],
//        ])->toArray();
//        $prodName = XHImsProduct::getProdEnum();
//        foreach ($prods as &$prod ) {
//            $prod->iProdId = $prodName[$prod->iProdId];
//        }
//        $this->view->setVars([
//            'header' => $receive,
//            'prods'  => $prods
//        ]);
//    }

    /**
     * 保存领用
     *
     * create by xjq 20180528
     * modify by qgz 20180719 增加状态
     */
    public function saveReceiveAction()
    {
        $postData = $this->request->getPost();
        if (!$postData['iReceiveId'] || !$postData['tApplyDate']) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        try {
            $prods = $this->request->getPost('prods');
            $existSIMId = '';
            if ($this->checkRepeat($prods)) {
                return $this->sendErrorResponse(400, '商品清单有重复');
            }
            if (!$this->checkTrueData($prods)) {
                return $this->sendSuccessResponse('没有需要领用的物品');
            }
            if (isset($postData['existPhoneNum'])) {//存在手机卡
                if (!$postData['phoneNum']) {
                    return $this->sendErrorResponse(400, '手机号不能为空');
                }
                $postData['phoneNum'] = trim($postData['phoneNum']);
                $existSIMId = $this->checkPhoneNum($postData);//检查手机号格式
                if (!$existSIMId) {
                    return $this->sendErrorResponse(400, '请输入正确手机号码，且个数要与手机卡数一致；多个用英文,隔开');
                }
            }
            $this->db->begin();
            if ($postData['iLRId']) {
                $receive = XHImsReceive::findFirst($postData);
            } else {
                $receive = new XHImsReceive();
            }
            $receive->iReceiveId = $postData['iReceiveId'];
            $receive->tApplyDate = $postData['tApplyDate'];
            $receive->sNumber    = $this->getNumber($postData['iReceiveId']);
            $receive->mDesc      = $postData['mDesc'];
            if (!$receive->save()) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '借用记录保存失败');
            }
            $existTrueData = false;
            foreach ($prods as $index => $prod) {
                if (!$prod['iProdId'] && !$prod['iNum']) {
                    continue;
                }
                $existTrueData = true;
                if ($prod['iPLId']) {
                    $node = XHImsReceiveProds::findFirst($prod['iPLId']);
                } else {
                    $node = new XHImsReceiveProds();
                }
                $node->sNumber = $receive->sNumber;
                $node->iKeyId  = $receive->iLRId;
                $node->iProdId  = $prod['iProdId'];
                $node->iNum     = $this->filter->sanitize($prod['iNum'], 'int');
                $node->bReceive = 1;//领用
                if (!$node->iNum) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '商品的数量不能为0');
                }
                $node->iStatus = $prod['iStatus'];//正常或报废
                if (isset($postData['existPhoneNum']) && $postData['phoneNum']
                    && $existSIMId && $existSIMId == $prod['iProdId']) {//手机卡
                    $node->sPhoneNum = $postData['phoneNum'];
                }
                if (!$node->save()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '商品列表保存失败');
                }
            }
            if (!$existTrueData) {
                $this->db->rollback();
                return $this->sendSuccessResponse('没有需要领用的物品');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('申请保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 检查是否都为空数据，有数据返回true
     *
     * @param $prods
     *
     * @return bool
     *
     * create by qgz 20181129
     */
    public function checkTrueData($prods)
    {
        $existTrueData = false;
        foreach ($prods as $index => $prod) {
            if (!$prod['iProdId'] && !$prod['iNum']) {
                continue;
            }
            $existTrueData = true;
        }
        return $existTrueData;
    }

    /**
     * 检测手机卡号数据，返回手机卡商品id
     *
     * @param $data
     *
     * @return bool
     *
     * create by qgz 20181122
     */
    public function checkPhoneNum($data)
    {
        $prodId = $data['prods'][$data['existPhoneNum'][0]]['iProdId'];
        $phoneNum = $data['prods'][$data['existPhoneNum'][0]]['iNum'];//手机号数量
        $phoneStr = $data['phoneNum'];//手机号字符串，逗号隔开
        $phoneArr = explode(',', $phoneStr);
        if (count($phoneArr) != $phoneNum) {
            return false;
        }
        foreach ($phoneArr as $item) {
            if (!$item || !$this->checkTel($item)) {//检测手机号是否正确
                return false;
            }
        }
        return $prodId;
    }

    /**
     * 检测是否正确的手机号
     *
     * @param $phoneNum
     *
     * @return bool
     *
     * create by qgz 20181122
     */
    public function checkTel($phoneNum)
    {
        if (preg_match("/^1[3456789]\d{9}$/", $phoneNum)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除领用清单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180530
     */
    public function delReceiveAction(){
        if (!UserPower::checkUserPower('Lm_Goods_Receive_Del')) {
            return $this->sendErrorResponse( 401 ,'没有权限');
        }
        try{
            $this->db->begin();
            $id = $this->request->getPost('iLRId' , 'int');
            $obj = XHImsReceive::findFirst($id);
            if ( !User::isAdmin() && $obj->iCreateUserId != Main::getLoginUserInfo('userId') ) {
                return $this->sendErrorResponse(401 , '没有权限');
            }
            $obj->bDelete = 1;
            if (!$obj->save()) {
                $this->db->rollback();
                return $this->sendErrorResponse(500 , '领用主表记录删除失败');
            }
            $nodes = XHImsReceiveProds::find([
                'conditions' => 'bDelete = 0 and iKeyId= :iKeyId: and bReceive = 1',
                'bind'       => ['iKeyId' => $obj->iLRId]
            ]);
            foreach ($nodes  as $node){
                $node->bDelete = 1;
                if (!$node->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500 , '领用子表记录删除失败');
                }
            }
            $outData = XHLmGoodsOut::find([
                'conditions' => 'bDelete = 0 and iOutTypeId = :iOutTypeId:',
                'bind'       => ['iOutTypeId' => $obj->iLRId]
            ]);
            foreach ($outData as $value){
	            $value->bDelete = 1;
	            if (!$value->save()){
		            $this->db->rollback();
		            return $this->sendErrorResponse(500, '出库关联记录删除失败', 'ID:'.$value->iId);
	            }
	            $findData = XHLmGoods::findFirst(['conditions' => 'bDelete = 0 AND iId = :id:', 'bind' => ['id' => $value->iGoodsId]]);
	            $num = Lm::getNumData('in', $value->iOutNum, $value->iOutType, $value->iOutStatus, $findData->iType);
	            $findData->iNum += $num['store'];
	            $findData->iAllNum += $num['all'];
	            if (!$findData->save()){
		            $this->db->rollback();
		            return $this->sendErrorResponse(500, '修改物品数量错误', 'ID:'.$findData->iId);
	            }

            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        }catch ( \Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500 , $e->getMessage());
        }

    }

    /**
     * 获取领用二维码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180529
     */
    public function getReceiveQRAction(){
        $number = $this->request->getPost('number', 'string');
        if (!$number) {
            return $this->sendErrorResponse(400, '缺少领用单号');
        }
        return $this->sendSuccessResponse(Tool::getQRBase64Uri(Tool::buildUrl('lm/receive/scanReceiveQR/'.$number.'?userId='.Main::getLoginUserInfo('userId'))), false);
    }

    /**
     * 扫码动作
     *
     * @param $number
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180530
     * modify by qgz 20180719 入库操作使用新表
     */
    public function scanReceiveQRAction($number = '')
    {
        $userId = $this->request->getQuery('userId');
        if (!$userId) {
            return $this->sendViewError('缺少用户id');
        }
        try {
            $this->db->begin();
            if (!$number) {
                return $this->sendViewError('缺少参数');
            }
            $obj = XHImsReceive::findFirst([
                'conditions' => 'bDelete = 0 and  sNumber = :sNumber: ',
                'bind'       => ['sNumber' => $number],
            ]);
            if (!$obj) {
                return $this->sendViewError('未找到该单号对应的领用清单');
            }

            if ($obj->iReceiveId != Main::getLoginUserInfo('userId')) {
                return $this->sendViewError('该清单并不属于你');
            }
            if ($obj->iState == 4) {
                return $this->sendViewError('该清单已经领用，请勿重复领用');
            }
            $nodes = XHImsReceiveProds::find([
                'columns'    => 'iProdId,iNum,iStatus,sPhoneNum',
                'conditions' => 'bDelete = 0 and iKeyId = :iKeyId: and bReceive = 1 ',
                'bind'       => ['iKeyId' => $obj->iLRId]
            ])->toArray();
            foreach ($nodes as $node) {
                $params = [
                    'id'         => $node['iProdId'],
                    'time'       => date('Y-m-d'),
                    'num'        => $node['iNum'],
                    'type'       => 2,//领取
                    'userId'     => $obj->iReceiveId,
                    'status'     => $node['iStatus'],
                    'remark'     => $obj->mDesc,
                    'outTypeId'  => $obj->iLRId,
                    'createUser' => $userId,
                    'phoneNum'   => $node['sPhoneNum']
                ];
                Lm::goodsOutHandle($params);
            }
            $obj->iState    = 4;
            $obj->tRealTime = date('Y-m-d H:i:s');
            if (!$obj->save()) {
                throw  new \Exception('领用记录保存失败');
            }
            $this->db->commit();

            return $this->sendViewSuccess('成功领用');
        } catch (\Exception $e) {
            $this->db->rollback();

            return $this->sendViewError($e->getMessage());
        }
    }



    /**
     * 商品出库
     * @param $iProdId
     * @param $iNum
     * @param $iLRId
     * @return bool
     * @throws \Exception
     * create by xjq 20180530
     */
    public function outProd($iProdId,$iNum,$iLRId){
        $boxes = XHImsBoxIn::find([
            'conditions' => 'bDelete = 0  and iState = 1 and iProdId = :iProdId:',
            'bind'       => ['iProdId' => $iProdId],
        ]);
        $prods = XHImsProdIn::find([
            'conditions' => 'bDelete = 0  and iState = 1 and iProdId = :iProdId: and iBoxId is null',
            'bind'       => ['iProdId' => $iProdId],
        ]);
        $total = 0;
        foreach ($boxes as $box) {
            $total += $box->iLeftNum;
        }
        $total += count($prods);
        if ($total < $iNum) {
           throw  new \Exception('库存不足');
        }
        foreach ($boxes as $box ) {
            $outBox = new XHImsBoxOut();
            if ($iNum >= $box->iLeftNum) {
                $iNum -= $box->iLeftNum;
                $outBox->iProdId = $box->iProdId;
                $outBox->iTypeId = $box->iTypeId;
                $outBox->iOutNum = $box->iLeftNum;
                $outBox->iBoxId  = $box->iBoxId;
                $outBox->iType   = 1;
                $outBox->iLRId   = $iLRId;
                $box->sRemark .= date('Y-m-d',time()).'领用出库：'.$box->iLeftNum.';';
                $box->iLeftNum = 0 ;
                $box->iState = 2;
            } else {
                $outBox->iProdId = $box->iProdId;
                $outBox->iTypeId = $box->iTypeId;
                $outBox->iOutNum = $iNum;
                $outBox->iBoxId  = $box->iBoxId;
                $outBox->iType   = 2;
                $outBox->iLRId   = $iLRId;
                $box->iLeftNum -= $iNum;
                $box->sRemark .= date('Y-m-d',time()).'领用出库：'.$iNum.';';
                $iNum  = 0;
            }
            if (!$box->save() || !$outBox->save()) {
                throw new \Exception('出库保存失败');
            }
            if ($iNum == 0) {
                return true;
            }
        }
        foreach ($prods as $prod) {
            if($iNum == 0){
                break;
            }
            $outProd = new XHImsProdOut();
            $outProd->iProdId = $prod->iProdId;
            $outProd->iTypeId = $prod->iTypeId;
            $outProd->iType   = 1;
            $outProd->iLRId   = $iLRId;
            $prod->iState = 2 ;
            $prod->sRemark = date('Y-m-d',time()).'领用出库';
            $iNum--;
            if ( !$prod->save() || !$outProd->save()) {
                throw new \Exception('出库保存失败');
            }
        }
        return true;
    }



    /**
     * 获取领用编号
     *
     * @param $userId
     * @param $isReceive
     * @return string
     * create by xjq 20180529
     */
    public function getNumber($userId ,$isReceive=true){
        do{
            $number = date('Ymd',time()).$userId.$this->getRandStr(6);
            if($isReceive){
                $check = XHImsReceive::findFirst([
                    'conditions' => 'bDelete = 0  and sNumber = :sNumber:',
                    'bind'      => ['sNumber' => $number]
                ]);
            }else{
                $check = XHImsReturn::findFirst([
                    'conditions' => 'bDelete = 0  and sNumber = :sNumber:',
                    'bind'      => ['sNumber' => $number]
                ]);
            }
            if (!$check) {
                break;
            }
        }while(true);
        return $number;
    }

    /**
     * 生成随机数
     *
     * @param $length
     * @return string
     * create by xjq 20180529
     */
    public function getRandStr($length){
        $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len=strlen($str)-1;
        $randStr='';
        for($i=0;$i<$length;$i++){
            $num=mt_rand(0,$len);
            $randStr .= $str[$num];
        }
        return $randStr;
    }


    /**
     * 验证是否重复
     *
     * @param $prods
     * @return bool
     * create by xjq 20180529
     * modify by qgz 20181129
     */
    public function checkRepeat($prods){
//        $nowNum  = count($prods);
//        $noRepeat = count(array_filter(array_unique(array_column($prods , 'iProdId'))));
//        return $noRepeat == $nowNum ? false : true;
        $existArr = [];
        foreach ($prods as $value) {
            if ($value['iProdId']) {
                if (in_array($value['iProdId'], $existArr)) {
                    return true;
                } else {
                    $existArr[] = $value['iProdId'];
                }
            }
        }
        return false;
    }


    /**
     * 归还列表
     *
     * create by xjq 20180515
     */
    public function returnListAction(){
        if (!UserPower::checkUserPower('Lm_Goods_Return')) {
            return $this->sendViewError('没有权限');
        }
	    Main::showNavPosition();
        Assets::easyUI();
        Assets::sweetAlert2();
        Assets::importJs('js/receive/returnList.js');
	    Assets::importMainJs('assets/easyui/datagrid-detailview.js');
        $this->view->pick('receive/returnList');
        Template::exists('returnList', 'list') or die(Main::showMessageModal('returnList 配置文件不存在，请先创建！', 109106002));
        $listButton = $listSearchArr = [];
        if(UserPower::checkUserPower('Lm_Goods_Return_Add')){
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if(UserPower::checkUserPower('Lm_Goods_Return_Del')){
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if (UserPower::checkUserPower('Lm_Goods_Return_Confirm')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_confirm', 'text' => '归还确认', 'icon' => 'fa-qrcode');
        }
        $receiveState = ['' => '--归还状态--'] + self::$returnState;
	    $consume = ['' => '--消耗品--'] + self::$goodsEnum['type'];
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_state', 'data' => $receiveState);
	    $listSearchArr[] = array('type' => 'select', 'id' => 'select_consume', 'data' => $consume);
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $this->view->setVars(array(
            'List' => Template::createList('list', 'returnList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButton),
            ])
        ));
    }

    /**
     * 获取物品归还
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180530
     */
    public function getReturnAction(){
        if (!UserPower::checkUserPower('Lm_Goods_Return')) {
            return $this->sendErrorResponse( 401 , '缺少权限');
        }
        $key   = $this->request->getPost('key','string');
        $state = $this->request->getPost('state' , 'string');
	    $consume = $this->request->getPost('consume');
	    try {
//		    $builder = $this->modelsManager->createBuilder()
//		                                   ->columns('r.iLRTId,r.iReturnId,u.sUserName,r.sNumber,r.tRealTime,r.tApplyDate,r.iState,r.bDelete,r.tCreateDate,r.iCreateUserId,r.tLastModifyDate,r.iLastModifyUserId,r.mDesc')
//		                                   ->from(['r' => 'Admin\\Models\\ims\\XHImsReturn'])
//		                                   ->leftJoin('Admin\\Models\\user\\XhsysUser','u.iUserId = r.iReturnId' ,'u')
//		                                   ->where('r.bDelete = 0 ')
//		                                   ->orderBy('r.tCreateDate DESC');
//		    if ($key) {
//			    $builder->andWhere('u.sUserName like :key:' , ['key' => '%' . $key . '%']);
//		    }

//		    if ($state || $state === '0' ) {
//			    $builder->andWhere('r.iState = :iState: ' , ['iState' => $state ]);
//		    }
//		    if(!User::isAdmin()){
//			    $nowUserId = Main::getLoginUserInfo('userId');
//			    $depArr = User::getExtraPower('dep', 'goodsReturn', $nowUserId);
//			    if($depArr){ //有额外权限
//				    $userIds = Hrm::getUserByDepId($depArr, true);
//				    if ($userIds) {
//					    $builder->andWhere('r.iCreateUserId in ({ids:array}) or r.iReturnId in ({userIds:array}) or r.iCreateUserId = :userId: or r.iReturnId = :nowUserId:',
//						    ['ids' => $userIds, 'userIds' => $userIds, 'userId' => $nowUserId, 'nowUserId' => $nowUserId]);
//				    } else {
//					    $builder->andWhere(' r.iCreateUserId = :userId: or r.iReturnId = :nowUserId:', ['userId' => $nowUserId, 'nowUserId' => $nowUserId]);
//				    }
//			    }else{
//				    $builder->andWhere(' r.iCreateUserId = :userId: or r.iReturnId = :nowUserId:', ['userId' => $nowUserId, 'nowUserId' => $nowUserId]);
//			    }
//		    }
		    $isConsume = false;
		    $condition = " a.bDelete = 0 ";
		    if (in_array($consume, ['0', '1'])){
			    $condition .= " AND a.iLRTId IN (SELECT b.iKeyId FROM `XHIms_ReceiveProds` b WHERE b.bDelete = 0 AND b.bReceive = 0 AND b.iProdId IN (
		        SELECT c.iId FROM `XHLm_Goods` c WHERE c.bDelete = 0 AND c.iType = {$consume} ))";
			    $isConsume = $consume;
		    }
		    if ($key) {
			    $condition .= " AND u.sStaffName LIKE '%".$key."%' ";
		    }
		    if ($state || $state === '0' ) {
			    $condition .= " AND a.iState = ".$state;
		    }
		    $sql = [
			    'columns' => "a.*, u.sStaffName as sUserName",
			    'query' => "SELECT :columns: FROM `XHIms_Return` a LEFT JOIN `XHHrm_Staff` u ON u.iUserId = a.iReturnId WHERE {$condition} ORDER BY a.tCreateDate DESC "
		    ];
		    $data = Main::runSqlPage($sql, ['iState' => self::$returnState]);

//		    $data = Main::runBuilderPage($builder,['iState' => self::$returnState]);
		    $ids = array_column($data['rows'] , 'iLRTId' );
		    $nodes = $this->getNodeArr($ids,0, $isConsume);
		    foreach ( $data['rows'] as $index => &$row ) {
			    $row['mProdList'] = isset($nodes[$row['iLRTId']]) ? $nodes[$row['iLRTId']] : [];
			    if ($row['mDesc']){
				    $row['mDesc'] = '<span title="'.$row['mDesc'].'">'.$row['mDesc'].'</span>';
			    }
                $staffInfo = Hrm::getStaffInfo([$row['iReturnId']]);
                if (isset($staffInfo[$row['iReturnId']])) {
                    $staffInfo = $staffInfo[$row['iReturnId']];
                    $row['sUserName'] .= $staffInfo['depName'] ? '(' . $staffInfo['depName'] . ')' : '';
                    $row['phoneNum'] = $staffInfo['phoneNumber'];
                }
		    }
		    unset($row);
		    Main::runUserNameById($data['rows'] , ['iCreateUserId' => 'iCreateUserId' , 'iLastModifyUserId' => 'iLastModifyUserId'] , true);
		    return $this->sendJsonResponse($data);
	    } catch ( \Exception $e ) {
		    return $this->sendErrorResponse( 500, $e->getMessage() );
	    }
    }


    /**
     * 获取领用表单
     *
     * create by xjq 20180515
     * modify by qgz 20180719 使用物品表数据
     */
    public function returnFormAction(){
        $this->view->pick('receive/returnForm');
        Assets::select2();
        Assets::importJs('js/receive/returnForm.js');
//        $staff = XhhrmStaff::find([
//            'columns' => 'iUserId,sStaffName',
//            'conditions' => 'bDelete= 0 and iStaffStatus = 1 and iUserId is not null'
//        ])->toArray();
	    $goods = XHLmGoods::find(['columns' => 'iId, sGoodsName', 'conditions' => 'bDelete = 0'])->toArray();
	    $goods = array_column($goods, 'sGoodsName', 'iId');
//        $staff = array_column($staff , 'sStaffName' , 'iUserId');
        $staff = Hrm::getUserWithDepName();
        if ($staff) {
            $staffInfoArr = Hrm::getStaffInfo(array_keys($staff));
            foreach ($staff as $key => &$item) {
                if (isset($staffInfoArr[$key]) && $staffInfoArr[$key]['phoneNumber']) {
                    $item .= '_' . $staffInfoArr[$key]['phoneNumber'];
                }
            }
        }
        $this->view->setVars([
            'staffs' => $staff,
            'prods'  => $goods,
        ]);
    }

    /**
     * 保存归还
     *
     * create by xjq 20180530
     * modify by qgz 20180719 增加状态
     */
    public function saveReturnAction()
    {
        $postData = $this->request->getPost();
        if( !$postData['iReturnId'] || !$postData['tApplyDate'] ) {
            return $this->sendErrorResponse(400 , '填写归还人和时间');
        }
        try{
            $prods = $this->request->getPost('prods');
            $existSIMId = '';
            if ($this->checkRepeat($prods)) {
                return $this->sendErrorResponse(400 , '商品清单有重复');
            }
            if (!$this->checkTrueData($prods)) {
                return $this->sendSuccessResponse('没有需要领用的物品');
            }
            if (isset($postData['existPhoneNum'])) {//存在手机卡
                if (!$postData['phoneNum']) {
                    return $this->sendErrorResponse(400, '手机号不能为空');
                }
                $postData['phoneNum'] = trim($postData['phoneNum']);
                $existSIMId = $this->checkPhoneNum($postData);//检查手机号格式
                if (!$existSIMId) {
                    return $this->sendErrorResponse(400, '请输入正确手机号码，且个数要与手机卡数一致；多个用英文,隔开');
                }
            }
            $this->db->begin();
            if ($postData['iLRTId']) {
                $return = XHImsReturn::findFirst($postData);
            }else{
                $return = new XHImsReturn();
            }
            $return->iReturnId  = $postData['iReturnId'];
            $return->tApplyDate = $postData['tApplyDate'];
            $return->sNumber    = $this->getNumber($postData['iReturnId'] , false);
            $return->mDesc      = $postData['mDesc'];
            if ( !$return->save() ) {
                $this->db->rollback();
                return $this->sendErrorResponse(500 , '归还记录保存失败');
            }
            $existTrueData = false;
            foreach ($prods as $index => $prod) {
                if (!$prod['iProdId'] && !$prod['iNum']) {
                    continue;
                }
                $existTrueData = true;
                if ($prod['iPLId']){
                    $node = XHImsReceiveProds::findFirst($prod['iPLId']);
                }else{
                    $node = new XHImsReceiveProds();
                }
                $node->sNumber = $return->sNumber;
                $node->iKeyId  = $return->iLRTId;
	            if (!$prod['iProdId']){
		            $this->db->rollback();
		            return $this->sendErrorResponse(400 , '物品不能为空');
	            }
                $node->iProdId = $prod['iProdId'];
                if (!$prod['iNum']){
	                $this->db->rollback();
	                return $this->sendErrorResponse(400 , '数量不能为空');
                }
                $node->iNum    = $prod['iNum'];
                $node->bReceive = 0; //归还
	            $node->iStatus = $prod['iStatus'];//正常或报废
                if (isset($postData['existPhoneNum']) && $postData['phoneNum']
                    && $existSIMId && $existSIMId == $prod['iProdId']) {//手机卡
                    $node->sPhoneNum = $postData['phoneNum'];
                }
                if ( !$node->save() ) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500 , '商品列表保存失败');
                }
            }
            if (!$existTrueData) {
                $this->db->rollback();
                return $this->sendSuccessResponse('没有需要领用的物品');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('申请保存成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }

    /**
     * 删除领用清单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180530
     */
    public function delReturnAction(){
        if (!UserPower::checkUserPower('Lm_Goods_Return_Del')) {
            return $this->sendErrorResponse( 401 ,'没有权限');
        }
        try{
            $this->db->begin();
            $id = $this->request->getPost('iLRTId' , 'int');
            $obj = XHImsReturn::findFirst($id);
//            if ($obj->iState == 4) {
//                return $this->sendErrorResponse(400 , '已归还的清单无法删除');
//            }
            if ( !User::isAdmin() && $obj->iCreateUserId != Main::getLoginUserInfo('userId') ) {
                return $this->sendErrorResponse(401 , '没有权限');
            }
            $obj->bDelete = 1;
            if (!$obj->save()) {
                $this->db->rollback();
                return $this->sendErrorResponse(500 , '删除失败');
            }
            $nodes = XHImsReceiveProds::find([
                'conditions' => 'bDelete = 0 and iKeyId= :iKeyId: and bReceive = 0',
                'bind'       => ['iKeyId' => $obj->iLRTId]
            ]);
            foreach ($nodes  as $node){
                $node->bDelete = 1;
                if (!$node->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500 , '领用子表记录删除失败');
                }
            }
            $inData = XHLmGoodsIn::find([
                'conditions' => 'bDelete = 0 and iInTypeId = :iInTypeId:',
                'bind'       => ['iInTypeId' => $obj->iLRTId]
            ]);
            foreach ($inData as $value){
	            $value->bDelete = 1;
	            if (!$value->save()){
		            $this->db->rollback();
		            return $this->sendErrorResponse(500, '入库关联记录删除失败', 'ID:'.$value->iId);
	            }
	            $findData = XHLmGoods::findFirst(['conditions' => 'bDelete = 0 AND iId = :id:', 'bind' => ['id' => $value->iGoodsId]]);
	            $num = Lm::getNumData('out', $value->iInNum, $value->iInType, $value->iInStatus, $findData->iType);
	            $findData->iNum -= $num['store'];
	            $findData->iAllNum -= $num['all'];
	            if (!$findData->save()){
		            $this->db->rollback();
		            return $this->sendErrorResponse(500, '修改物品数量错误', 'ID:'.$findData->iId);
	            }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        }catch ( \Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }


    /**
     * 获取领用二维码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180529
     */
    public function getReturnQRAction(){
        $number = $this->request->getPost('number', 'string');
        if (!$number) {
            return $this->sendErrorResponse(400, '缺少领用单号');
        }
        return $this->sendSuccessResponse(Tool::getQRBase64Uri(Tool::buildUrl('lm/receive/scanReturnQR/'.$number.'?userId='.Main::getLoginUserInfo('userId'))));
    }


    /**
     * 归还扫码动作
     *
     * @param $number
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180530
     */
    public function scanReturnQRAction($number=''){
        $userId = $this->request->getQuery('userId');
        if (!$userId) {
            return $this->sendViewError('缺少userId');
        }
        try{
            $this->db->begin();
            if (!$number) {
                return $this->sendViewError( '缺少参数');
            }
            $obj = XHImsReturn::findFirst([
                'conditions' => 'bDelete = 0 and  sNumber = :sNumber: ',
                'bind'       => ['sNumber' =>  $number],
            ]);
            if (!$obj) {
                return $this->sendViewError('未找到该单号对应的领用清单');
            }
            if ($obj->iReturnId != Main::getLoginUserInfo('userId') ){
                return $this->sendViewError( '该清单并不属于你');
            }
            if($obj->iState  == 4){
                return $this->sendViewError('该清单已经归还，请勿重复归还');
            }
            $nodes = XHImsReceiveProds::find([
                'columns'    => 'iProdId, iNum, iStatus, sPhoneNum',
                'conditions' => 'bDelete = 0 and iKeyId = :iKeyId: and bReceive = 0',
                'bind'       => ['iKeyId' => $obj->iLRTId]
            ])->toArray();
            foreach ($nodes as $node) {
	            $params = [
		            'id' => $node['iProdId'],
		            'time' => date('Y-m-d'),
		            'num' => $node['iNum'],
		            'type' => 2,//归还
		            'userId' => $obj->iReturnId,
		            'status' => $node['iStatus'],
		            'remark' => $obj->mDesc,
		            'inTypeId' => $obj->iLRTId,
		            'createUser' => $userId,
                    'phoneNum'   => $node['sPhoneNum']
	            ];
	            Lm::goodsInHandle($params);
            }
            $obj->iState = 4;
            $obj->tRealTime = date('Y-m-d H:i:s');
            if (!$obj->save()) {
                throw  new \Exception('归还记录保存失败');
            }
            $this->db->commit();
            return $this->sendViewSuccess('成功归还');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendViewError( $e->getMessage());
        }
    }

    /**
     * 入库保存
     *
     * @param $prodId
     * @param $num
     * @param $iLRTId
     * @return bool
     * @throws \Exception
     * create by xjq 20180530
     */
    public function inProd($prodId,$num,$iLRTId){
        $typeId = XHImsProduct::findFirst($prodId)->iTypeId;
        if ($num == 1) {
            $obj = new XHImsProdIn();
            $obj->iProdId = $prodId;
            $obj->iState  = 1;
            $obj->sRemark = date('Y-m-d').'归还入库';
            $obj->iLRTId  = $iLRTId;
            $obj->iTypeId = $typeId;
        } else if ($num > 1) {
            $obj = new XHImsBoxIn();
            $obj->iProdId = $prodId;
            $obj->iState  = 1;
            $obj->sRemark = date('Y-m-d').'归还入库,数量:'.$num;
            $obj->iLRTId  = $iLRTId;
            $obj->iTypeId = $typeId;
            $obj->iProdNum = $num;
            $obj->iLeftNum = $num;
        }else{
            throw  new \Exception('商品数量不能为负数');
        }
        if (!$obj->save() ) {
            throw new \Exception('商品入库保存失败');
        }
        return true;
    }



}